from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
import logging

from app.database.connection import get_db
from app.models.movie import Movie
from app.services.recommendation_service import get_recommendation_service_instance, RecommendationService
from app.services.maoyan_api_service import maoyanApiService
from app.services.tmdb_api_service import TMDBApiService
from app.services.auth_service import AuthService
from app.routers.auth import get_current_user
from app.models.user import User


router = APIRouter(prefix="/recommendation",tags=["电影推荐"])

# 提供猫眼API服务实例
def get_maoyan_api_service():
    return maoyanApiService

# 提供推荐服务单例实例
def get_recommendation_service():
    return get_recommendation_service_instance()


# 获取正在热映电影
@router.get("/hot-movies", response_model=List[Movie], summary="热映电影")
async def get_hot_movies(
    limit: int = 20,
    service: RecommendationService = Depends(get_recommendation_service)
):
    return await service.get_hot_movies(limit)

# 获取即将上映电影
@router.get("/coming-soon-movies", response_model=List[Movie], summary="即将上映电影")
async def get_coming_soon_movies(
    ci: int = 10,
    limit: int = 10,
    service: RecommendationService = Depends(get_recommendation_service)
):
    return await service.get_coming_soon_movies(ci, limit)

# 根据电影ID获取电影详情
@router.get("/movie-detail/{movie_id}", response_model=Movie, summary="获取电影详情")
async def get_movie_detail(
    movie_id: int,
    source: str = None,  # 电影来源："maoyan" 或 "tmdb"
    service: RecommendationService = Depends(get_recommendation_service)
):
    try:
        movie = await service.get_movie_detail(movie_id, source)
        if not movie:
            raise HTTPException(status_code=404, detail="电影未找到")
        return movie
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取电影详情失败: {str(e)}")


@router.get("/personalized", response_model=List[Movie])
async def get_personalized_recommendations(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    service: RecommendationService = Depends(get_recommendation_service)
):
    """获取个性化推荐电影"""
    try:
        movies = await service.get_personalized_recommendations(current_user.id, db)
        return movies
    except Exception as e:
        logging.error(f"获取个性化推荐失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取个性化推荐失败: {str(e)}")


@router.delete("/personalized/cache")
async def clear_personalized_cache(
    current_user: User = Depends(get_current_user),
    service: RecommendationService = Depends(get_recommendation_service)
):
    """清除个性化推荐缓存"""
    try:
        service.clear_personalized_cache(current_user.id)
        return {"message": "个性化推荐缓存已清除"}
    except Exception as e:
        logging.error(f"清除个性化推荐缓存失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清除个性化推荐缓存失败: {str(e)}")